import os
from pywinauto.application import Application
import pywinauto
import time

def qwaddfri(telNum):
    # 通过CMD启动微信
    # os.system('cd C:\Program Files（Others）\WXWork && WXWork.exe')
    # 连接微信
    app = Application(backend='uia').connect(class_name='WeWorkWindow')
    # 获取窗口
    win_main_dialog = app.window(class_name="WeWorkWindow")
    win_main_dialog.restore()
    # 第一次获取窗口坐标
    x1 = win_main_dialog.rectangle().left
    y1 = win_main_dialog.rectangle().top
    x2 = win_main_dialog.rectangle().right
    y2 = win_main_dialog.rectangle().bottom
    # 模拟鼠标按住缩小窗口
    pywinauto.mouse.press(coords=(x2, y2))
    pywinauto.mouse.release(coords=(0, 0))
    # 第二次获取窗口坐标（缩小后的窗口）
    x1 = win_main_dialog.rectangle().left
    y1 = win_main_dialog.rectangle().top
    x2 = win_main_dialog.rectangle().right
    y2 = win_main_dialog.rectangle().bottom
    win_main_dialog.set_focus()
    pywinauto.keyboard.send_keys('^f')

    # 输入手机号
    win_main_dialog.type_keys('^a').type_keys(telNum, with_spaces=True)
    # 点击网络查找手机/邮箱
    time.sleep(0.5)
    pywinauto.mouse.click(coords=(x1+345, y1+105))
    # 网络查找手机/邮箱弹窗
    time.sleep(1)
    add_main_win = app.window(class_name="SearchExternalsWnd")
    a = add_main_win.rectangle().left
    b = add_main_win.rectangle().right

    x3 = (add_main_win.rectangle().right + add_main_win.rectangle().left)/2
    y3 = (add_main_win.rectangle().bottom + add_main_win.rectangle().top)/2

    if b - a <= 400:
        pywinauto.mouse.click(coords=(int(x3)+150, int(y3)-15))
    else:
        pywinauto.mouse.click(coords=(int(x3)+186,int(y3)-15))
    # 点添加
    # 输入验证消息并点发送
    time.sleep(0.5)

    verify_main_pane = add_main_win.child_window(title="输入认证信息", control_type="Pane")

    x4 = verify_main_pane.rectangle().left
    y4 = verify_main_pane.rectangle().bottom
    x3 = verify_main_pane.rectangle().right
    y3 = verify_main_pane.rectangle().top
    pywinauto.mouse.click(coords=(int((x3-x4)/2 + x4), int((y4-y3)/2+y3+45)))
    # 关闭添加好友窗口
    time.sleep(0.5)
    pywinauto.keyboard.send_keys("{ESC}")

if __name__ == '__main__':
    qwaddfri('17673156819')
